package gr.gsis.cobol.my;

import gr.gsis.cobol.data.Formatter;
import gr.gsis.cobol.spec.FieldSpec;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;

public class MyDecimalFormatter implements Formatter {

	private int getScale(FieldSpec spec) {
		return spec.getPicture().length() - spec.getPicture().indexOf('V') - 1;
	}

	@Override
	public Object toObject(FieldSpec spec, String value) throws Exception {
		BigInteger bi = new BigInteger(value);
		BigDecimal bd = new BigDecimal(bi, getScale(spec));

		return bd;
	}

	@Override
	public String toString(FieldSpec spec, Object value) throws Exception {
		BigDecimal bd = (BigDecimal) value;
		DecimalFormat format = new DecimalFormat(
				spec.getPicture().replaceAll("9", "0").replaceAll("V", ""));
		
		return format.format(bd.movePointRight(getScale(spec)));
	}

}
